<template>
	<view class="content">
		<tui-navigation-bar :titleSize="18" :titleLineHeight="18" :titlefontWeight="800" :isOpacity="false"
			@init="initNavigation" :title="title" backgroundColor="#fff" color="#000">
			<image class="exit-icon position-absolute top-0 right-0 status-bar-height mr-2" src="/static/exit.png"
				mode="aspectFill" style="width:40rpx;height: 40rpx;" @click="logout"></image>
		</tui-navigation-bar>
		<view :style="{ marginTop: marginTp + 'px' }"></view>
		<!-- 根据 currentComponent 动态加载组件 -->
		<ShopControl :beUserId="beUserId" :userShopDetails="shopDetails" v-if="currentComponent === 'ShopControl'" />
		<DistributionControl v-if="currentComponent === 'DistributionControl'" />
		<AppraiseControl v-if="currentComponent === 'AppraiseControl'" />
		<TutorControl :ossUrl="ossUrl" :marginTp="marginTp" v-if="currentComponent === 'TutorControl'" />
		<!-- <mine v-if="currentComponent === 'mine'" /> -->
		<tui-tabbar @clickTabbar="clickTabbar"></tui-tabbar>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import Cache from "@/utils/cache";
	import AppraiseControl from './appraiseControl/appraiseControl.vue'
	import DistributionControl from './distributionControl/distributionControl.vue'
	import ShopControl from './shopControl/shopControl.vue'
	import TutorControl from './tutorControl/tutorControl.vue'
	import mine from './mine/mine.vue'
	export default {
		data() {
			return {
				top: 0, //标题图标距离顶部距离
				marginTp: 0,
				beUserId: '',
				ossUrl: getApp().globalData.ossurl, //图片前缀
				title: '店铺管理',
				currentComponent: 'ShopControl', // 默认显示商户管理
				shopDetails: {}
			}
		},
		components: {
			ShopControl,
			DistributionControl,
			AppraiseControl,
			TutorControl,
			mine
		},
		onLoad() {
			uni.$emit('refresh', true)
			this.checkauthorize()
		},
		methods: {
			...mapMutations(['changeTabItem', 'changeTabBar']),
			initNavigation(e) {
				this.top = e.top;
				this.marginTp = e.height
			},
			// 定位授权
			checkauthorize() {
				let self = this

				// #ifdef MP-WEIXIN
				uni.getSetting({
					success(res) {
						if (!res.authSetting['scope.userLocation']) {
							uni.authorize({
								scope: 'scope.userLocation',
								success: () => { //这里是用户同意授权后的回调
									self.getLocation();
								},
								fail: () => { //这里是用户拒绝授权后的回调
									self.rejectSetting()
								}
							})
						} else { //用户已经授权过了
							self.getLocation();
						}
					}
				})
				// #endif

				// #ifdef APP-PLUS
				// APP端需要先检查权限
				this.checkAppLocationPermission();
				// #endif

				// #ifndef MP-WEIXIN || APP-PLUS
				this.getLocation();
				// #endif
			},
			// 检查APP位置权限
			checkAppLocationPermission() {
				// #ifdef APP-PLUS
				const self = this;
				// 获取当前系统信息
				const systemInfo = uni.getSystemInfoSync();
				// 判断是否是安卓系统
				const isAndroid = systemInfo.platform.toLowerCase() === 'android';

				if (isAndroid) {
					// 安卓平台需要动态申请权限
					const permissions = [
						'android.permission.ACCESS_FINE_LOCATION',
						'android.permission.ACCESS_COARSE_LOCATION'
					];

					plus.android.requestPermissions(
						permissions,
						function(resultObj) {
							// 检查是否有已授权的权限
							let hasLocationPermission = false;
							for (let i = 0; i < resultObj.granted.length; i++) {
								const grantedPermission = resultObj.granted[i];
								if (permissions.includes(grantedPermission)) {
									hasLocationPermission = true;
									break;
								}
							}

							if (hasLocationPermission) {
								// 有位置权限，获取位置
								self.getLocation();
							} else {
								// 没有位置权限，提示用户
								uni.showModal({
									title: '提示',
									content: '需要位置权限才能正常使用应用，请在设置中开启',
									confirmText: '去设置',
									success: function(res) {
										if (res.confirm) {
											// 打开应用设置页面
											self.openAppPermissionSettings();
										}
									}
								});
							}
						},
						function(error) {
							console.error('权限请求失败:', error);
						}
					);
				} else {
					// iOS平台直接请求位置权限
					self.getLocation();
				}
				// #endif
			},

			// 打开应用权限设置页面
			openAppPermissionSettings() {
				// #ifdef APP-PLUS
				if (uni.getSystemInfoSync().platform.toLowerCase() === 'android') {
					// 安卓平台
					const Intent = plus.android.importClass("android.content.Intent");
					const Settings = plus.android.importClass("android.provider.Settings");
					const Uri = plus.android.importClass("android.net.Uri");
					const mainActivity = plus.android.runtimeMainActivity();
					const intent = new Intent();
					intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
					const uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
					intent.setData(uri);
					mainActivity.startActivity(intent);
				} else {
					// iOS平台
					const UIApplication = plus.ios.import("UIApplication");
					const application = UIApplication.sharedApplication();
					const NSURL = plus.ios.import("NSURL");
					const setting = NSURL.URLWithString("app-settings:");
					application.openURL(setting);
					plus.ios.deleteObject(setting);
					plus.ios.deleteObject(NSURL);
					plus.ios.deleteObject(application);
				}
				// #endif
			},
			// 获取当前定位的经纬度
			getLocation() {
				let self = this
				uni.getLocation({
					type: 'gcj02',
					success: function(res) {
						//经纬度转换成省市区 latitude纬度，long经度
						self.$utils.getAddress(res.latitude, res.longitude,
							'661f987dcae58c7cb089e589ad3c7b18', (obj) => {
								Cache.set('adressNmae', obj.name);
								Cache.set('city', obj.city);
							});
					},
					fail: (err) => {
						console.error('定位失败:', err);
						// #ifdef APP-PLUS
						// APP端定位失败，可能是权限问题，重新检查权限
						if (uni.getSystemInfoSync().platform.toLowerCase() === 'android') {
							self.checkAppLocationPermission();
						}
						// #endif
					}
				})
			},
			// 用户拒绝授权后的回调
			rejectSetting() {
				var that = this;
				uni.showModal({
					title: '警告',
					content: '授权失败，请打开位置消息授权',
					success: (res) => {
						if (res.confirm) { //去授权
							that.toOpenSetting();
						} else if (res.cancel) { //用户点击取消
							console.log(res);
							uni.showModal({
								title: '提示',
								content: '获取权限失败，将无法获取定位哦~',
								showCancel: false,
								success: (res) => {
									that.toOpenSetting();
								}
							})
						}
					}
				})
			},
			//打开微信设置页面
			toOpenSetting() {
				// #ifdef MP-WEIXIN
				uni.openSetting({
					success: (e) => {
						console.log(e);
					}
				})
				// #endif

				// #ifdef APP-PLUS
				this.openAppPermissionSettings();
				// #endif
			},
			// 分类数据
			getCategoryListData() {
				getCategoryList().then(res => {
					if (res.code == 200) {
						this.tabs = res.data;
						this.selCategoryId = res.data[0].id;
						uni.setStorageSync('categoryList', res.data);
					} else {
						this.$utils.toast("首页-分类 " + res.msg);
					}
				}).catch(error => {
					this.$utils.toast("首页-分类 " + error);
				})
			},
			back() {
				uni.navigateBack({
					delta: 1
				});;
			},
			clickTabbar(detils) {
				this.changeTabBar({
					index: detils.index
				})
				if (detils.index === 0) {
					this.currentComponent = 'ShopControl'
					this.title = '店铺管理'
				} else if (detils.index === 1) {
					this.currentComponent = 'DistributionControl'
					this.title = '分销管理'
				} else if (detils.index === 2) {
					this.currentComponent = 'AppraiseControl'
					this.title = '评价管理'
				} else if (detils.index === 3) {
					this.currentComponent = 'TutorControl'
					this.title = '教练管理'
				} else {
					// this.currentComponent = 'mine'
					// this.title = '个人中心'
				}
			},
			logout() {
				Cache.claer()
				uni.reLaunch({
					url: '/pages/userLogin/userLogin'
				})
			}
		}
	}
</script>

<style scoped>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.tui-header-icon {
		width: 100%;
		position: fixed;
		top: 0;
		padding: 0 0 0 38rpx;
		display: flex;
		align-items: center;
		height: 32px;
		transform: translateZ(0);
		z-index: 99999;
		box-sizing: border-box;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>